<template>
    <div style="border: 1px solid #ccc">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" />
        <Editor style="height: 200px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
            @onCreated="handleCreated" />
    </div>
</template>
  
<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, watch, watchEffect } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'


// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    }
})
const emits = defineEmits<{
    (e: 'update:modelValue', value: string): void
}>()

// 内容 HTML
const valueHtml = ref('<p>开端大全</p>')

//只要 modelValue变化就会触发函数
watchEffect(() => {
    valueHtml.value = props.modelValue
})
// valueHtml变化才会执行第2个参数
watch(valueHtml, (newValue, oldValue) => {
    emits("update:modelValue", newValue)
})


const toolbarConfig = {
    menus: ['source-code', /* ...other menus */],
}
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {
        uploadImage: {
            server: '/api/v1/m/upload',
            fieldName: 'file',
            // 自定义插入图片
            customInsert(res: any, insertFn: InsertFnType) {  // TS 语法
                // customInsert(res, insertFn) {                  // JS 语法
                // res 即服务端的返回结果

                // 从 res 中找到 url alt href ，然后插入图片
                if(res.code ===0){
                    let url = res.data.url
                    let href = url
                    let alt = res.data.name
                    insertFn(url, alt, href)
                }
            },
        }
    }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
</script>   